package com.example.rocketmq.base.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 消息消费
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        // 创建消费者，指定消费者组名，通过broker推送来消费
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("sync_consumer");
        // 指定nameserver地址
        consumer.setNamesrvAddr("192.168.228.101:9876;192.168.228.103:9876");
        // 订阅topic 和 tag
        consumer.subscribe("base", "tag1");
        // 设置消费模式，负载均衡或广播，默认是负载均衡
        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 设置回调，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
                list.stream().map(Message::getBody).forEach(e -> System.out.println(new String(e)));
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
        // 启动消费者
        consumer.start();
    }
}
